/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import entity.xml.EMessaggio;
import entity.xml.EUtente;
import foundation.FMessaggi;
import foundation.FUtenti;
import java.awt.FlowLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jdom.JDOMException;
import presentation.proportional.PBacheca;
import presentation.proportional.gui;

/**
 *
 * @author Ennio
 */
public class CBacheca {
    
    private static CBacheca istance= null;
    private ArrayList<EUtente> userList;
    private ArrayList<EMessaggio> msgSentList;
    private ArrayList<EMessaggio> msgReceivedList;
    private EUtente currUser;
    private EUtente currContact;
    private HashMap conversations;
    
    
    
    private CBacheca(){
        
    }
    
    public ArrayList<EMessaggio> getMsgReceivedList() {
        return msgReceivedList;
    }

    public void setMsgReceivedList(ArrayList<EMessaggio> msgReceivedList) {
        this.msgReceivedList = msgReceivedList;
    }

    public ArrayList<EMessaggio> getMsgSentList() {
        return msgSentList;
    }

    public void setMsgSentList(ArrayList<EMessaggio> msgSentList) {
        this.msgSentList = msgSentList;
    }
    
    public static CBacheca getIstance(){
        
        if(istance==null) istance= new CBacheca();
        
        return istance;
        
    }
    
    public EUtente getCurrUser() {
        return currUser;
    }

    public void setCurrUser(EUtente currUser) {
        this.currUser = currUser;
    }

    public ArrayList<EUtente> getUserList() {
        return userList;
    }

    public void setUserList(ArrayList<EUtente> userList) {
        this.userList = userList;
    }
    
    public void loadUsers(){
        
        try {
            
            this.userList= FUtenti.getIstance().getListaUtenti();
            this.currUser= new EUtente();
            
            
            Object[] choices = new Object[this.userList.size()];
            
            for(int i=0 ; i<this.userList.size(); i++){
            
                choices[i]= this.userList.get(i).getNickname();
                
            }
            
            String ans= (String) JOptionPane.showInputDialog(null, "Selezionare il profilo con cui accedere", "SELEZIONE UTENTE", JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]);
            boolean flag= false;
            for(int i=0 ; i<this.userList.size(); i++){
                
                if(this.userList.get(i).getNickname()==ans){ 
                    
                    this.currUser= this.userList.get(i);
                    flag= true;
                    
                }
                
            }
            
            
        } catch (JDOMException ex) {
            Logger.getLogger(PBacheca.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PBacheca.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public ArrayList<EMessaggio> orderConversationsByDate(ArrayList<EMessaggio> messagesConversation){
        
        Collections.sort(messagesConversation);
        return messagesConversation;
        
        /*
        for(int k=0; k<messagesConversation.size(); k++){
            messagesConversation.get(k).printMsg();
        }
        */
    }
    
    public HashMap orderTotalMessagesByDate(HashMap hm){
        
        ArrayList<Entry<String,ArrayList<EMessaggio>>> entries = new ArrayList<Entry<String,ArrayList<EMessaggio>>>( hm.entrySet() );  
        Collections.sort( entries , new Comparator() {  
           public int compare( Object o1 , Object o2 )  
           {  
               Map.Entry e1 = (Map.Entry)o1 ;  
               Map.Entry e2 = (Map.Entry)o2 ;  
               ArrayList<EMessaggio> first = (ArrayList<EMessaggio>)e1.getValue();  
               ArrayList<EMessaggio> second = (ArrayList<EMessaggio>)e2.getValue(); 
               return first.get(0).compareTo( second.get(0) );
           }  
        });  
        HashMap<String,ArrayList<EMessaggio>> newMap = new LinkedHashMap<String,ArrayList<EMessaggio>>();
        for(Entry<String,ArrayList<EMessaggio>> entry : entries){
           newMap.put(entry.getKey(), entry.getValue());
        }
        return newMap;
       
   }
        
        
        
        
        
    
    public HashMap orderMsgByDate(HashMap hm){
        
        Set set = hm.entrySet();
        Iterator i = set.iterator(); 
        while(i.hasNext()) {
            Map.Entry me = (Map.Entry)i.next(); 
            ArrayList<EMessaggio> lis= (ArrayList<EMessaggio>)me.getValue();
            hm.put(me.getKey(), this.orderConversationsByDate(lis));
        }
        
        hm= this.orderTotalMessagesByDate(hm);
        this.printHashMap(hm);
        
        return hm;
        
    }
    
    public void printHashMap(HashMap hm){
        
        /*System.out.println("=====================   INIZIO HASH MAP !!!!!!   ==========================");
        
        Set set = hm.entrySet();
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            
            Map.Entry me = (Map.Entry)i.next(); 
            ArrayList<EMessaggio> lis= (ArrayList<EMessaggio>)me.getValue();
            
            System.out.println("INIZIO CONVERSAZIONE !!!!!!   ==========================");
            
            for(int k=0; k<lis.size(); k++){
                
                lis.get(k).printMsg();
            
            }
            
            System.out.println("FINE CONVERSAZIONE !!!!!!   ==========================");
            
        }
        
        System.out.println("=====================   FINE HASH MAP !!!!!!   ==========================");
         * 
         */
        
    }
    
    public HashMap getHashMapFromArrayList(ArrayList<EMessaggio> listaTotalMsg){
        HashMap hash= new HashMap();
        ArrayList<EMessaggio> lis;
        for(int i=0; i<listaTotalMsg.size(); i++){
            
            String keyHash= "";
            keyHash = Integer.toString(listaTotalMsg.get(i).getIDConversazione());
            keyHash += "-" + listaTotalMsg.get(i).getMittente().getNickname();
            for(int k=0; k<listaTotalMsg.get(i).getDestinatario().size(); k++){
                keyHash += "-" + listaTotalMsg.get(i).getDestinatario().get(k).getNickname();
            }
            //creare key hash invertita
            System.out.println(keyHash);
            
            String keyHashInverted= "";
            keyHashInverted = Integer.toString(listaTotalMsg.get(i).getIDConversazione());
            for(int k=0; k<listaTotalMsg.get(i).getDestinatario().size(); k++){
                keyHashInverted += "-" + listaTotalMsg.get(i).getDestinatario().get(k).getNickname();
            }
            keyHashInverted += "-" + listaTotalMsg.get(i).getMittente().getNickname();
            
            String currentHash=keyHash;
            
            if(!(hash.containsKey(keyHash) ||hash.containsKey(keyHashInverted)) ){ 
                lis= new ArrayList<EMessaggio>();
            }
            else{
                if(!hash.containsKey(currentHash))currentHash=keyHashInverted;
                lis= (ArrayList<EMessaggio>) hash.get(currentHash); 
            }
            lis.add(listaTotalMsg.get(i));
            hash.put(currentHash, lis);
            
        }
        return hash;
    
    }
    
    public HashMap getConversationsOfUser(EUtente us){
        
        this.setMessageOfUser(us);
        
        //ArrayList<EMessaggio> listaMsgByIDConv= new ArrayList<EMessaggio>();
        ArrayList<EMessaggio> listaTotalMsg= new ArrayList<EMessaggio>();
        
        listaTotalMsg.addAll(this.msgSentList);
        listaTotalMsg.addAll(this.msgReceivedList);
        
        this.conversations= this.getHashMapFromArrayList(listaTotalMsg);
      
        Set set = this.conversations.entrySet();
        Iterator i = set.iterator(); 
        while(i.hasNext()) { 
            
            Map.Entry me = (Map.Entry)i.next(); 
            
            ArrayList<EMessaggio> alis= (ArrayList<EMessaggio>)me.getValue();
            for(int k=0; k<alis.size(); k++){
                
                alis.get(k).printMsg();
                
            }
            
        }
        
        return this.conversations;
    }
    
    public void setMessageOfUser(EUtente us){
        
        this.msgSentList= new ArrayList<EMessaggio>();
        this.msgSentList= FMessaggi.getIstance().getMsgBySender(us);
        
        this.msgReceivedList= new ArrayList<EMessaggio>();
        this.msgReceivedList= FMessaggi.getIstance().getMsgByReceiver(us);
        
        //this.printMessageOfUser();
        
    }
    public void setCurrContact(EUtente contatto){
        this.currContact=contatto;
    }
    public void setBachecaContact(EUtente contatto){
        
        this.currContact=contatto;
        PBacheca.getInstance().refreshPanel(contatto);
        gui.getIstance().buttonClicked("vaiBachecaContatto");
    }
    public int getMaxIDConversazione(EUtente mittente, ArrayList<EUtente> destinatario){
        
        int maxIDConv= 1;
        
        for(int i=0; i<this.msgSentList.size(); i++){
            
            for(int k=0; k<destinatario.size(); k++){
            
                if(this.msgSentList.get(i).getMittente().getNickname().equals(mittente.getNickname()) &&
                    this.msgSentList.get(i).getDestinatario().get(k).getNickname().equals(destinatario.get(k).getNickname())){

                    int currIDConv= this.msgSentList.get(i).getIDConversazione();
                    if(currIDConv>maxIDConv) maxIDConv= currIDConv;
                }
                
            }
                
        }
        //System.out.println("Massimo id conversazione tra " + mittente.getNickname() + " e " + destinatario.getNickname() + " e' : " + maxIDConv + "./n");
        
        return maxIDConv;
        
    }
    
    public void printMessageOfUser(){
            
        for(int i=0; i<this.msgReceivedList.size(); i++){
        
            this.msgReceivedList.get(i).printMsg();
            
        }
        
        for(int i=0; i<this.msgSentList.size(); i++){
        
            this.msgSentList.get(i).printMsg();
            
        }
        
    }
    
    
    
}
